#include "event_record.h"
#include <chrono>
#include <stdio.h>

namespace rr {
namespace nio {

static std::map<uint32_t, std::string> kEventTypeMap = {
    {EventRecord::Type::UNKNOWN, "Unknown"},
    {EventRecord::Type::ASYNC, "ASYNC"},
    {EventRecord::Type::TCP, "TCP"},
    {EventRecord::Type::TIMER, "TIMER"}
};

static std::string EventTypeToString(EventRecord::Type type)
{
    auto it = kEventTypeMap.find(type);
    if(it != kEventTypeMap.end()) {
        return it->second;
    }
    return "Unknown";
}

EventRecord::EventRecord(Type type, void* event_ptr)
: type_(type)
, event_ptr_(event_ptr)
{
    auto time_now = std::chrono::system_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(time_now.time_since_epoch());
    timestamp_ = (int64_t)duration.count();
}

EventRecord::~EventRecord()
{

}

///

EventRecorder::EventRecorder()
{

}

EventRecorder::~EventRecorder()
{

}

void EventRecorder::Dump()
{
    printf("dump event records begin\n");
    for(auto& it : records_) {
        printf("time:%llu event_ptr: %p, event_type: %s\n",
               it.second->timestamp_, it.second->event_ptr_, EventTypeToString(it.second->type_).c_str());
    }
    printf("dump event records end\n");
}

void EventRecorder::AddRecord(const EventRecord::Sptr& record)
{
    auto it = records_.find((uint64_t)record->event_ptr_);
    if(it != records_.end()) {
        printf("add record %p type:%s isexist\n", record->event_ptr_, EventTypeToString(record->type_).c_str());
    }

    printf("add record %p type:%s\n", record->event_ptr_, EventTypeToString(record->type_).c_str());
    records_[(uint64_t)record->event_ptr_] = record;
}

void EventRecorder::RemoveRecord(void *event_ptr)
{
    uint64_t key = (uint64_t)event_ptr;
    auto it = records_.find(key);
    if(it != records_.end()) {
        printf("remove record %p type:%s\n", it->second->event_ptr_, EventTypeToString(it->second->type_).c_str());
        records_.erase(it);
    }

    return;
}

} //namespace 
} //namespace 
